import { useEffect, useState } from 'react';
import { useSharedValue } from 'react-native-reanimated';
import { useFrameProcessor } from 'react-native-vision-camera';
import { VisionCameraProxy } from 'react-native-vision-camera';

/**
 * 自定义Hook用于获取和管理AR数据
 */
export const useARData = () => {
  // 使用SharedValue存储AR数据，以便在worklet和JS线程间共享
  const arData = useSharedValue<any>(null);
  const [arDataJS, setArDataJS] = useState<any>(null);
  // 管理中心点到摄像头的距离
  const distance = useSharedValue<number | null>(null);
  const [distanceJS, setDistanceJS] = useState<number | null>(null);

  // 创建帧处理器获取AR数据
  const frameProcessor = useFrameProcessor(frame => {
    'worklet';
    // 初始化ARCore插件，传递两个点的坐标用于计算距离
    const centerX = frame.width / 2;
    const centerY = frame.height / 2;

    const plugin = VisionCameraProxy.initFrameProcessorPlugin('arcore', {
      textureId: 0,
      point1X: centerX - 50,
      point1Y: centerY,
      point2X: centerX + 50,
      point2Y: centerY,
    });
    const info = plugin ? plugin.call(frame) : {};
    // console.log('ARCore info:', info);
    // 更新AR数据
    if (info && typeof info === 'object') {
      if ('error' in info) {
        if (info.isHuaweiDevice) {
          console.log('华为设备提示:', info.error);
          // 可以提示用户安装华为AR Engine
        } else {
          console.log('AR错误:', info.error);
        }
      } else {
        arData.value = info;

        // 如果有有效的AR数据，计算中心点到摄像头的距离
        if (
          typeof info === 'object' &&
          info !== null &&
          'tx' in info &&
          'ty' in info &&
          'tz' in info &&
          typeof info.tx === 'number' &&
          typeof info.ty === 'number' &&
          typeof info.tz === 'number'
        ) {
          // 计算相机位置到原点(0,0,0)的距离
          const dist = Math.sqrt(
            info.tx * info.tx + info.ty * info.ty + info.tz * info.tz,
          );
          distance.value = dist;
        }

        // 如果有hitTest距离，则使用hitTest距离
        if (
          typeof info === 'object' &&
          info !== null &&
          'hitDistance' in info &&
          typeof info.hitDistance === 'number'
        ) {
          distance.value = info.hitDistance;
        }

        // 如果有两点间距离，则使用该距离
        if (
          typeof info === 'object' &&
          info !== null &&
          'pointsDistance' in info &&
          typeof info.pointsDistance === 'number'
        ) {
          distance.value = info.pointsDistance;
        }
      }
    }
  }, []);

  // 监听AR数据变化并更新到JS状态
  useEffect(() => {
    const interval = setInterval(() => {
      if (arData.value) {
        setArDataJS(arData.value);
      }
      if (distance.value !== null) {
        setDistanceJS(distance.value);
      }
    }, 100); // 每100ms更新一次

    return () => clearInterval(interval);
  }, []);

  return {
    frameProcessor,
    arData: arDataJS,
    distance: distanceJS,
  };
};
